/****************************************************************************************
 * Copyright (c) 2010~2012 All Rights Reserved by
 * G-Net Integrated Service Co.,  Ltd. 
 ****************************************************************************************/
/**
 * @file DESEncrypt.java
 *
 * @author pujun.deng
 *
 * @date 2012-10-3 上午09:36:58
 *
 *       
 * Revision History 
 *     - 2012-10-3: change content for what reason
 ****************************************************************************************/

package com.oc.mba.util;

import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * @brief DES加密解密工具类
 * 
 */
public class DESEncrypt {
	// 生成16进制随机数
	// PASSWORD_CRYPT_KEY= Integer.toHexString(new Random().nextInt());
	private static String PASSWORD_CRYPT_KEY = null; // /<加密串，从参会人数据库中获得，如果没有则声称一个8位16进制的随机串
	private final static String DES = "DES"; // /<加密方式 DES
	private static final int DEFAUT_ZERO_INT = 0;
	private static final int DESKEY_BYTES_NUM = 8;
	public static final String CHARSET_UTF8="UTF-8";

	/**
	 * @brief 构造方法，传入DESKey
	 * @param cryptkey
	 *            加密串，从参会人数据库中获得，如果没有则声称一个8位16进制的随机串
	 */
	public DESEncrypt(String cryptkey) {
		PASSWORD_CRYPT_KEY = cryptkey;
	}

	/**
	 * @brief 生成DESKey(8位)
	 * @param userid 用户数据库中的id
	 * @return DESKey
	 */
	public static String createDESkey(long userid) {
		int deskeyint = (int) (userid + new Random().nextInt());
		String hexString = Integer.toHexString(deskeyint);
		int length = hexString.length();
		if (length < DESKEY_BYTES_NUM) {
			for (int i = DEFAUT_ZERO_INT; i < DESKEY_BYTES_NUM
					- length; i++) {
				hexString = hexString + DEFAUT_ZERO_INT;
			}
		}
		if (length > DESKEY_BYTES_NUM) {
			hexString = hexString.substring(DEFAUT_ZERO_INT,
					hexString.length() - (length - DESKEY_BYTES_NUM));
		}
		return hexString;
	}

	/**
	 * @brief 生成DESKey
	 * @param hexLength desKey长度
	 * @return DESKey
	 */
	public static String createDESKeyByLength(int hexLength) {
		int deskeyint = (int) (new Random().nextInt());
		String hexString = Integer.toHexString(deskeyint);
		int length = hexString.length();
		if (length < hexLength) {
			for (int i = DEFAUT_ZERO_INT; i < hexLength - length; i++) {
				hexString = hexString + DEFAUT_ZERO_INT;
			}
		}
		if (length > hexLength) {
			hexString = hexString.substring(DEFAUT_ZERO_INT, hexString.length() - (length - hexLength));
		}
		return hexString;
	}

	/**
	 * @brief 加密
	 * @param src
	 *            数据源
	 * @param key
	 *            密钥，长度必须是8的倍数
	 * @return 返回加密后的数据
	 * @throws Exception
	 */
	private static byte[] encrypt(byte[] src, byte[] key) throws Exception {

		// DES算法要求有一个可信任的随机数源

		SecureRandom sr = new SecureRandom();

		// 从原始密匙数据创建DESKeySpec对象

		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密匙工厂，然后用它把DESKeySpec转换成

		// 一个SecretKey对象

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);

		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成加密操作

		Cipher cipher = Cipher.getInstance(DES);

		// 用密匙初始化Cipher对象

		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		// 现在，获取数据并加密

		// 正式执行加密操作

		return cipher.doFinal(src);

	}

	/**
	 * @brief 解密
	 * @param src
	 *            数据源
	 * @param key
	 *            密钥，长度必须是8的倍数
	 * @return 返回解密后的原始数据
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src, byte[] key) throws Exception {

		// DES算法要求有一个可信任的随机数源

		SecureRandom sr = new SecureRandom();
		// 从原始密匙数据创建一个DESKeySpec对象

		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密匙工厂，然后用它把DESKeySpec对象转换成

		// 一个SecretKey对象

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);

		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成解密操作

		Cipher cipher = Cipher.getInstance(DES);

		// 用密匙初始化Cipher对象

		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

		// 现在，获取数据并解密

		// 正式执行解密操作

		return cipher.doFinal(src);

	}

	/**
	 * @brief 参数解密
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public final static String decrypt(String data) {

		try {

			return new String(decrypt(
					hex2byte(data.getBytes(CHARSET_UTF8)),

					PASSWORD_CRYPT_KEY.getBytes(CHARSET_UTF8)));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * @brief 参数加密
	 * @param data
	 *            需要加密的参数
	 * @return 加密后的结果
	 * @throws Exception
	 */

	public final static String encrypt(String data) {

		try {
			byte[] dataBytes = data.getBytes(CHARSET_UTF8);
			// System.out.print("dataBytes===========");
			// for(int i=0;i<dataBytes.length;i++){
			// System.out.print(dataBytes[i]+",");
			// }
			// System.out.println("");
			byte[] desKeyBytes = PASSWORD_CRYPT_KEY.getBytes(CHARSET_UTF8);
			byte[] encryptStringBytes = encrypt(dataBytes, desKeyBytes);
			// System.out.print("加密后的字节===========");
			// for(int i=0;i<encryptStringBytes.length;i++){
			// System.out.print(encryptStringBytes[i]+",");
			//
			// }
			// System.out.println("");
			String encryptString = byte2hex(encryptStringBytes);
			return encryptString;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @brief 二行制转字符串
	 * @param b
	 *            byte数组
	 * @return 转换后的结果
	 */
	private static String byte2hex(byte[] b) {

		String hs = "";

		String stmp = "";

		for (int n = 0; n < b.length; n++) {

			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));

			if (stmp.length() == 1)

				hs = hs + "0" + stmp;

			else

				hs = hs + stmp;

		}

		return hs.toUpperCase();

	}

	/**
	 * @brief 二行制转字符串
	 * @param b
	 *            byte数组
	 * @return 转换后的结果
	 */
	private static byte[] hex2byte(byte[] b) {
		// System.out.println(b.length);
		if ((b.length % 2) != 0)

			throw new IllegalArgumentException("长度不是偶数");

		byte[] b2 = new byte[b.length / 2];

		for (int n = 0; n < b.length; n += 2) {

			String item = new String(b, n, 2);

			b2[n / 2] = (byte) Integer.parseInt(item, 16);

		}

		return b2;
	}
	// public static void main(String args[]){
	// // SysLog.info(className, DESEncrypt.createDESkey(1));
	// //8eb3a1600
	// createDESkey(9);
	// String hexString = "8eb3a16111";
	// int length = hexString.length();
	// if(length<8){
	// for(int i=0;i<8-length;i++){
	// hexString = hexString+"0";
	// }
	// }
	// if(length>8){
	// hexString = hexString.substring(0, hexString.length()-(length-8));
	// }
	// SysLog.info(hexString);
	// }
	// //
	
	public static void main(String[] args) {
		String orderID = "order123";
		String key = DESEncrypt.createDESKeyByLength(6);
		System.out.println("key=" + key);
		
		DESEncrypt dESEncrypt = new DESEncrypt(key);
		String encryptStr = dESEncrypt.encrypt(orderID);
		System.out.println("encryptStr=" + encryptStr);
		String decryptStr = dESEncrypt.decrypt(encryptStr);
		System.out.println("decryptStr=" + decryptStr);
	}
}
